package com.example.music.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.music.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class LocalMusicFragment extends Fragment {

    private ViewPager2 viewPager;
    private TabLayout tabLayout;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 加载布局
        View view = inflater.inflate(R.layout.fragment_local_music, container, false);

        // 初始化ViewPager2和TabLayout
        viewPager = view.findViewById(R.id.view_pager);
        tabLayout = view.findViewById(R.id.tab_layout);

        // 设置Adapter
        LocalMusicPagerAdapter adapter = new LocalMusicPagerAdapter(requireActivity());
        viewPager.setAdapter(adapter);

        // 绑定TabLayout与ViewPager2
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            switch (position) {
                case 0: tab.setText("单曲"); break;
                case 1: tab.setText("专辑"); break;
                case 2: tab.setText("歌手"); break;
                case 3: tab.setText("文件夹"); break;
            }
        }).attach();

        // 默认选中单曲Tab
        viewPager.setCurrentItem(0);

        return view;
    }

    // ViewPager2的Adapter
    private static class LocalMusicPagerAdapter extends FragmentStateAdapter {
        public LocalMusicPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            switch (position) {
                case 0: return SongsFragment.newInstance(SongsFragment.SortType.BY_SONG);
                case 1: return CategoryFragment.newInstance(CategoryFragment.CategoryType.BY_ALBUM);
                case 2: return CategoryFragment.newInstance(CategoryFragment.CategoryType.BY_ARTIST);
                case 3: return CategoryFragment.newInstance(CategoryFragment.CategoryType.BY_FOLDER);
                default: throw new IllegalArgumentException();
            }
        }

        @Override
        public int getItemCount() {
            return 4;
        }
    }
}
